package com.api.volunteer.controller;

import com.api.volunteer.service.AccountService;
import com.api.volunteer.service.SecretKeyService;
import com.api.volunteer.util.Holder;
import com.api.volunteer.util.Result;
import com.api.volunteer.vo.AccountVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @date 2022/3/31 16:08
 */
@RestController
public class AccountController extends BaseController{

    @Autowired
    AccountService accountService;

    @Autowired
    SecretKeyService secretKeyService;

    @Autowired
    Holder holder;

    private final Logger logger = LoggerFactory.getLogger(AccountController.class);

    /**
     * 用户第三次补全信息
     * 创建账户
     * @param accountVo 前端传输的账号vo对象
     * @return 响应结果
     */
    @PostMapping("/submitAccountInfo")
    public Result submit(@RequestBody AccountVo accountVo) throws InterruptedException {
        accountService.save(accountVo);
        return this.processSuceess();
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile image) {
        InputStream inputStream = null;
        try {
            inputStream = image.getInputStream();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return accountService.upload(image.getOriginalFilename(), Optional.ofNullable(inputStream).orElseThrow(()->{return new RuntimeException("上传空文件");}));
    }

    @PostMapping("/accountAudit")
    public Result accountAudit(@RequestParam("allow-secret-key") String secret, @RequestParam("openid") String openid){
        if(secretKeyService.findSecret(secret)){

            accountService.audit(openid);

            return this.processSuceess();
        }
        return new Result().put("code", 400);
    }

    /**
     * 获取当前用户的openid
     * @return
     */
    @GetMapping("/getCurrentOpenid")
    public String getOpenid(){
         return holder.getUser().getOpenid();
    }
}
